﻿using System;
using System.Collections.Concurrent;

namespace NetworkLibrary
{
    public abstract class BasePool<T>
    {
        private readonly ConcurrentStack<T> _pool;
        public BasePool()
        {
            _pool = new ConcurrentStack<T>();
        }
        protected abstract T CreateItem();
        public void Despawn(T item)
        {
            if (item == null)
                throw new ArgumentNullException("Items added to a SocketAsyncEventArgsPool cannot be null");
            _pool.Push(item);
        }
        public T Spawn()
        {
            if (_pool.TryPop(out var item))
            {
                return item;
            }
            return CreateItem();
        }
        public int Count
        {
            get { return _pool.Count; }
        }
        public void Clear()
        {
            _pool.Clear();
        }
    }

    public class Pool<T> : BasePool<T>
    {
        private Func<T> _creater;
        public Pool(Func<T> creater)
        {
            _creater = creater;
        }

        protected override T CreateItem()
        {
            return _creater();
        }
    }
}
